import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lily
 * Date: 2024-09-27
 * Time: 18:26
 */
public class rot_Apple {

    /**
     * @param grid int整型ArrayList<ArrayList<>>
     * @return int整型
     */
    static int[] dx = {-1, 1, 0, 0};
    static int[] dy = {0, 0, 1, -1};

    public int rotApple(ArrayList<ArrayList<Integer>> grid) {
        int n = grid.size();
        int m = grid.get(0).size();
        int[][] vis = new int[n][m];
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid.get(i).get(j) == 2)
                    queue.add(new int[]{i, j});
            }
        }

        int ret=0;
        while (!queue.isEmpty()){
            //每一轮
            int sz=queue.size();
            while (sz--!=0){
                int[] t=queue.poll();
                int a=t[0],b=t[1];
                for (int i = 0; i < 4; i++) {
                        int x=a+dx[i],y=b+dy[i];
                        if (x>=0&&x<n&&y>=0&&y<m&&vis[x][y]==0&&grid.get(x).get(y)==1){
                            vis[x][y]=1;
                            queue.add(new int[]{x,y});
                        }

                }
            }
            ret++;
        }
        // 判断剩余的苹果
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < m; j++)
            {
                if(grid.get(i).get(j) == 1 && vis[i][j]==0)
                {
                    return -1;
                }
            }
        }
        return ret;
    }

    public static void main(String[] args) {

    }
}
